import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-sys-permission-edit',
  templateUrl: './edit.component.html'
})
export class SysPermissionEditComponent implements OnInit {
  record: any = {};
  i: any;
  listOfGroupOption: Array<{ label: string; value: string }> = [];
  validateForm: FormGroup;
  controlsConfig = {
    ID: [null, null],
    name: ['', [Validators.required]],
    uri: ['', [Validators.required]],
    method: ['', [Validators.required]],
    group: [[], []],
    desc: ['', []],
    super: [0, [Validators.required]]
  };

  constructor(private modal: NzModalRef, private msgSrv: NzMessageService, public http: _HttpClient, private fb: FormBuilder) {
    this.validateForm = this.fb.group(this.controlsConfig);
  }

  ngOnInit(): void {
    this.loadPermissionGroups();
    if (this.record.ID > 0) {
      this.http.get(`api/permission/${this.record.ID}`).subscribe(res => {
        res.data.group = [res.data.group];
        this.validateForm.patchValue(res.data);
        this.i = res.data;
      });
    }
  }

  save(value: any): void {
    value.group = value.group[0];
    if (value.ID) {
      this.http.put(`api/permission/${this.record.ID}`, value).subscribe(res => {
        if (res.err_code != 0) {
          this.msgSrv.success(res.msg);
          return;
        }
        this.msgSrv.success('更新成功！');
        this.modal.close(true);
      });
    } else {
      this.http.post(`api/permission`, value).subscribe(res => {
        if (res.err_code != 0) {
          this.msgSrv.success(res.msg);
          return;
        }
        this.msgSrv.success('保存成功！');
        this.modal.close(true);
      });
    }
  }

  close(): void {
    this.modal.destroy();
  }

  loadPermissionGroups(): void {
    this.http.get(`api/permission_groups`).subscribe(res => {
      const children: Array<{ label: string; value: string }> = [];
      const groups = res.data;
      for (let i = 0; i < groups.length; i++) {
        children.push({ label: groups[i], value: groups[i] });
      }
      this.listOfGroupOption = children;
    });
  }
}
